import {defineStore} from 'pinia'
import {Product} from '../api'
import {useProductStore} from "./product";
import {buyProduct} from "../api/index";

type CartProduct = {
    num:number
} & Omit<Product,'inventory'> // Omit是过滤,过滤掉inventory属性，然后和num拼接起来

export const useCartStore = defineStore('cart',{
    state:() => {
        return {
            cartProducts:[] as CartProduct[],
            settleStatus:null as null | string
        }
    },

    getters:{
        // 总价
        totalPrice(state){
            return state.cartProducts.reduce((total,item) => {
                return total + item.price * item.num
            },0)
        }
    },

    actions:{
        // 添加商品到购物车
        addProductToCart(product:Product){
            // 检查购物车中是否有此商品，有则数量+1，没有则新增
            const cartItem = this.cartProducts.find(item => item.id === product.id)
            if(cartItem){
                cartItem.num++
            }else {
                this.cartProducts.push({
                    id:product.id,
                    title:product.title,
                    price:product.price,
                    num:1
                })
            }

            // 添加完商品之后需要更新库存
            const productStore = useProductStore()
            productStore.decrementProduct(product)
        },

        // 获取结算状态
        async getSettleStatus(){
            const res = await buyProduct()
            this.settleStatus = res ? '成功' : '失败'
            if(res){
                this.cartProducts = [] // 清空购物车
            }
        }
    }
})
